<!-- src/components/RoleManagementModal.vue -->
<template>
  <div class="modal-overlay" @click.self="close">
    <div class="modal-content">
      <div class="modal-header">
        <h3>角色与权限管理</h3>
        <button class="close-btn" @click="close">×</button>
      </div>

      <div class="role-management">
        <!-- 添加角色 -->
        <div class="section">
          <h4>添加新角色</h4>
          <div class="form-group">
            <input v-model="newRole.roleName" placeholder="角色名称" class="input-field">
            <input v-model="newRole.description" placeholder="角色描述" class="input-field">
            <button class="btn-add" @click="addRole">添加角色</button>
          </div>
        </div>

        <!-- 分配用户角色 -->
        <div class="section">
          <h4>分配用户角色</h4>
          <div class="form-group">
            <select v-model="userRoleAssignment.userId" class="input-field">
              <option value="">选择用户</option>
              <option v-for="user in users" :key="user.id" :value="user.id">
                {{ user.username }}
              </option>
            </select>
            <select v-model="userRoleAssignment.roleId" class="input-field">
              <option value="">选择角色</option>
              <option v-for="role in roles" :key="role.id" :value="role.id">
                {{ role.roleName }}
              </option>
            </select>
            <button class="btn-assign" @click="assignUserRole">分配角色</button>
          </div>
        </div>

        <!-- 添加权限 -->
        <div class="section">
          <h4>添加新权限</h4>
          <div class="form-group">
            <input v-model="newPermission.permissionName" placeholder="权限名称" class="input-field">
            <input v-model="newPermission.resourceUrl" placeholder="资源路径" class="input-field">
            <select v-model="newPermission.method" class="input-field">
              <option value="">选择方法</option>
              <option value="GET">GET</option>
              <option value="POST">POST</option>
              <option value="PUT">PUT</option>
              <option value="DELETE">DELETE</option>
            </select>
            <input v-model="newPermission.description" placeholder="权限描述" class="input-field">
            <button class="btn-add" @click="addPermission">添加权限</button>
          </div>
        </div>

        <!-- 分配角色权限 -->
        <div class="section">
          <h4>分配角色权限</h4>
          <div class="form-group">
            <select v-model="rolePermissionAssignment.roleId" class="input-field">
              <option value="">选择角色</option>
              <option v-for="role in roles" :key="role.id" :value="role.id">
                {{ role.roleName }}
              </option>
            </select>
            <select v-model="rolePermissionAssignment.permissionId" class="input-field">
              <option value="">选择权限</option>
              <option v-for="permission in permissions" :key="permission.id" :value="permission.id">
                {{ permission.permissionName }}
              </option>
            </select>
            <button class="btn-assign" @click="assignRolePermission">分配权限</button>
          </div>
        </div>
      </div>

      <div class="modal-actions">
        <button class="btn-cancel" @click="close">关闭</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';
import { permissionApi } from '@/api/user';
import { 
  AddRoleRequest, 
  AssignUserRoleRequest, 
  AddPermissionRequest, 
  AssignRolePermissionRequest 
} from '@/models/user';

export default {
  name: 'RoleManagementModal',
  emits: ['close'],
  setup(props, { emit }) {
    const newRole = ref(new AddRoleRequest());
    const newPermission = ref(new AddPermissionRequest());
    const userRoleAssignment = ref(new AssignUserRoleRequest());
    const rolePermissionAssignment = ref(new AssignRolePermissionRequest());
    
    // 模拟数据
    const users = ref([
      { id: 1, username: 'admin' },
      { id: 2, username: 'teacher1' },
      { id: 3, username: 'student1' }
    ]);
    
    const roles = ref([
      { id: 1, roleName: '管理员' },
      { id: 2, roleName: '教师' },
      { id: 3, roleName: '学生' }
    ]);
    
    const permissions = ref([
      { id: 1, permissionName: '用户管理' },
      { id: 2, permissionName: '课程管理' },
      { id: 3, permissionName: '成绩管理' }
    ]);

    const addRole = async () => {
      if (!newRole.value.roleName.trim()) {
        alert('请输入角色名称');
        return;
      }
      
      try {
        const response = await permissionApi.addRole(newRole.value);
        if (response.data.code === '000000') {
          alert('角色添加成功');
          newRole.value = new AddRoleRequest();
        } else {
          alert('添加失败: ' + response.data.msg);
        }
      } catch (error) {
        console.error('添加角色失败:', error);
        alert('操作失败: ' + (error.response?.data?.message || error.message));
      }
    };

    const assignUserRole = async () => {
      if (!userRoleAssignment.value.userId || !userRoleAssignment.value.roleId) {
        alert('请选择用户和角色');
        return;
      }
      
      try {
        const response = await permissionApi.assignUserRole(userRoleAssignment.value);
        if (response.data.code === '000000') {
          alert('角色分配成功');
          userRoleAssignment.value = new AssignUserRoleRequest();
        } else {
          alert('分配失败: ' + response.data.msg);
        }
      } catch (error) {
        console.error('分配角色失败:', error);
        alert('操作失败: ' + (error.response?.data?.message || error.message));
      }
    };

    const addPermission = async () => {
      if (!newPermission.value.permissionName.trim()) {
        alert('请输入权限名称');
        return;
      }
      
      try {
        const response = await permissionApi.addPermission(newPermission.value);
        if (response.data.code === '000000') {
          alert('权限添加成功');
          newPermission.value = new AddPermissionRequest();
        } else {
          alert('添加失败: ' + response.data.msg);
        }
      } catch (error) {
        console.error('添加权限失败:', error);
        alert('操作失败: ' + (error.response?.data?.message || error.message));
      }
    };

    const assignRolePermission = async () => {
      if (!rolePermissionAssignment.value.roleId || !rolePermissionAssignment.value.permissionId) {
        alert('请选择角色和权限');
        return;
      }
      
      try {
        const response = await permissionApi.assignRolePermission(rolePermissionAssignment.value);
        if (response.data.code === '000000') {
          alert('权限分配成功');
          rolePermissionAssignment.value = new AssignRolePermissionRequest();
        } else {
          alert('分配失败: ' + response.data.msg);
        }
      } catch (error) {
        console.error('分配权限失败:', error);
        alert('操作失败: ' + (error.response?.data?.message || error.message));
      }
    };

    const close = () => {
      emit('close');
    };

    return {
      newRole,
      newPermission,
      userRoleAssignment,
      rolePermissionAssignment,
      users,
      roles,
      permissions,
      addRole,
      assignUserRole,
      addPermission,
      assignRolePermission,
      close
    };
  }
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 700px;
  max-width: 90vw;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #666;
}

.role-management {
  padding: 20px;
}

.section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.section:last-child {
  border-bottom: none;
}

.section h4 {
  margin-bottom: 15px;
  color: #2c3e50;
}

.form-group {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.input-field {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  min-width: 150px;
}

.btn-add, .btn-assign {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  white-space: nowrap;
}

.btn-add {
  background-color: #3498db;
  color: white;
}

.btn-assign {
  background-color: #2ecc71;
  color: white;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  padding: 20px;
  border-top: 1px solid #eee;
}

.btn-cancel {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  background: #f5f5f5;
  color: #666;
  cursor: pointer;
}
</style>